const express = require("express")
const router = express.Router()
const articleDB = require("../../db/article")
const fs = require("fs")
const path = require("path")

const articleMap = {
  0: "新闻资讯",
  1: "公益作用",
  2: "以往公益记录",
}

// 获取文章
router.get("/find", async (req, res) => {
  try {
    const { isAll, type, limit, skip } = req.query

    // 查询所有
    if (isAll === "true") {
      const articleList = await articleDB
        .find(
          { type: type * 1 },
          {},
          { sort: { time: -1 }, limit: limit * 1, skip: skip * 1 }
        )
        .populate("author", { name: 1, avatar: 1 })
      const allNums = await (await articleDB.find({ type: type * 1 })).length
      res.send({
        code: 0,
        mes: `${articleMap[type]}全部数据`,
        data: {
          articleList,
          allNums,
        },
      })
    }
    // 只查询选中展示的
    else {
      const articleList = await articleDB
        .find(
          { isShow: true, type: type * 1 },
          {},
          { sort: { time: -1 }, limit: limit * 1, skip: skip * 1 }
        )
        .populate("author", { name: 1, avatar: 1 })
      const allNums = await articleDB.find({ isShow: true, type: type * 1 })
      res.send({
        code: 0,
        mes: `${articleMap[type]}数据`,
        data: {
          articleList,
          allNums,
        },
      })
    }
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

// 获取文章详细信息
router.get("/findInfo", async (req, res) => {
  try {
    const { articleID } = req.query
    // 查询文章是否存在
    const doc = await articleDB
      .findById(articleID)
      .populate("author", { name: 1, avatar: 1 })
    if (!doc)
      return res.send({
        code: 2,
        mes: "该文章已被删除，请刷新后重试",
      })
    res.send({
      code: 0,
      mes: "文章信息",
      data: {
        articleInfo: doc,
      },
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

// 获取文章富文本信息
router.get("/findEditorInfo", async (req, res) => {
  try {
    const { editorUrl } = req.query
    let editor = ""
    fs.readFile(
      path.join(__dirname, `../../static${editorUrl}`),
      (err, data) => {
        editor = data?.toString()
        if (!err) {
          res.send({
            code: 0,
            mse: "文章内容",
            data: {
              editor,
            },
          })
        } else {
          res.send({
            code: 5,
            mes: "异常",
          })
        }
      }
    )
  } catch (error) {
    console.log(error)
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

// 搜索文章关键字 获取文章列表
router.get("/search", async (req, res) => {
  try {
    const { type, name, limit, skip } = req.query
    const doc = await articleDB.find({ type: type * 1 }).populate("author", {
      name: 1,
      avatar: 1,
    })
    let articleList = doc.filter((item) => item.title.includes(name))
    if (skip == 0) {
      articleList.slice(skip * 1, limit * 1)
    } else {
      articleList.slice(skip * 1, limit * 1 + skip * 1)
    }
    const allNums = articleList.length
    res.send({
      code: 0,
      mes: "搜索文章列表",
      data: {
        articleList,
        allNums,
      },
    })
  } catch (error) {
    console.log(error)
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

// 添加文章
router.use("", require("./add"))

// 修改文章
router.use("", require("./update"))

// 删除文章
router.use("", require("./delete"))

module.exports = router
